package com.im.passport.controller;

import com.im.passport.exception.BusinessException;
import com.im.passport.pojo.User;
import com.im.passport.response.Result;
import com.im.passport.response.ResultCode;
import com.im.passport.service.UserService;
import com.im.passport.utils.RedisUtil;
import com.im.passport.utils.Utility;
//import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenmin
 * @date 2023/5/13
 */
@RestController
@RequestMapping("/user")
public class PassportController {

    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;

    @RequestMapping("/login/{username}/{password}")
    public Result login(@PathVariable("username") String username, @PathVariable("password") String password){
        User user = userService.getUserInfoByUsername(username);
//        System.out.println(user);
//        System.out.println(password);
        if(user == null || !user.getPassword().equals(password)){
            throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),
                    ResultCode.USER_CREDENTIALS_ERROR.getMessage());
        }
        String token = Utility.md5(Utility.uuid());
        System.out.println(token);
//        Map<String, Object> res = new HashMap<>();
//        res.put("token", token);
        redisUtil.setex(token, user, 7200);
        return Result.ok().data("token", token);
    }

    @RequestMapping("/token/{token}")
    public Result verify(@PathVariable("token") String token){
        User user = (User) redisUtil.get(token);
        if(user == null){
            throw new BusinessException(ResultCode.USER_ACCOUNT_EXPIRED.getCode(),
                    ResultCode.USER_ACCOUNT_EXPIRED.getMessage());
        }
        return Result.ok().data("username", user.getUsername());
    }

}
